<?php

namespace App\Admin\Extensions\Form;

use Encore\Admin\Form\Field;
use Encore\Admin\Extension;

class Simplemde extends Field
{
    /**
     * @var string
     */
    protected $view = 'admin-ext.form.simplemde';

    /**
     * @var array
     */
    protected static $css = [
        'vendor/laravel-admin-ext/simplemde/dist/simplemde.min.css',
        '//cdn.jsdelivr.net/highlight.js/latest/styles/monokai-sublime.min.css'
    ];

    /**
     * @var array
     */
    protected static $js = [
        'vendor/laravel-admin-ext/simplemde/dist/simplemde.min.js',
        '//cdn.jsdelivr.net/highlight.js/latest/highlight.min.js',
        '//cdnjs.cloudflare.com/ajax/libs/codemirror/4.0.3/codemirror.js'
    ];

    /**
     * @var int
     */
    protected $height = 300;

    /**
     * @param int $height
     * @return $this
     */
    public function height($height = 300)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $this->addVariables([
            'height'     => $this->height,
            'scopeClass' => 'simplemde-'.uniqid()
        ]);

        $name = $this->formatName($this->column);

        $default = [
            'renderingConfig' => [
                'singleLineBreaks' => false,
                'codeSyntaxHighlighting' => true,
            ]
        ];
        $config = (array) Extension::config('config');

        $config = json_encode(array_merge($config, $default));

        $varName = 'simplemde_'.uniqid();
        $url = admin_url('image/upload');

        $this->script = <<<EOT

var options = {element: $("#{$this->id}")[0]};

Object.assign(options, {$config});

var $varName = new SimpleMDE(options);

$varName.codemirror.on("change", function(){
	var html = $varName.value();
    $('input[name=$name]').val(html);
});

// 拖曳图片
$varName.codemirror.on('drop', function (editor, e) {
    if (!e.dataTransfer && e.dataTransfer.files) {
        alert('浏览器不支持此操作');
        return;
    }
    var dataList = e.dataTransfer.files;
    // 处理图片批量上传
    batchUpload(dataList, 'drop');
});

// 粘贴图片
$varName.codemirror.on('paste', function (editor, e) {
    if (!e.clipboardData && e.clipboardData.files) {
        alert('浏览器不支持此操作');
        return;
    }
    var dataList = (e.clipboardData || window.clipboardData).items;
    
    batchUpload(dataList, 'paste');
});

// 处理图片批量上传
function batchUpload(dataList, event) {
    if (!dataList || dataList.length == 0) {
        return;
    }
    
    for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].type.indexOf('image') === -1) {
            continue;
        }
        
        let image, imageSize, formData = new FormData();
        if (event === 'drop') {
            image = dataList[i];
        } else if (event === 'paste') {
            image = dataList[i].getAsFile();
        }
        
        if (!image) {
            console.log('粘贴内容非图片');
        }
        
        if ((imageSize = image.size / 1024 / 1024) > 2) {
            console.log('文件大小：' + imageSize + 'MB, 上传图片超过限制');
            return;
        }
        
        formData.append('image', image);
        
        fileUpload(formData);
    }
}

// ajax上传图片
function fileUpload(formData) {
    formData.append('_token', LA.token);
    $.ajax({
        url: "{$url}",
        type: 'POST',
        cache: false,
        data: formData,
        dataType: 'json',
        timeout: 5000,
        processData: false,
        contentType: false,
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            if (data && data.code == 1) {
                // 将返回的图片url追加到编辑器内
                $varName.value($varName.value() + "\\n ![" + data.data.originalName + "](" + data.data.url + ") \\n");
            } else {
                alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            alert("上传图片出错了");
        }
    });
}

EOT;
        return parent::render();
    }
}